<?php
ignore_user_abort(true);	// 忽略用户输入
set_time_limit(0); // 设置超时间

include("../config/function.inc.php");
include("../config/config.inc.php");
include("../config/QuickMySQL.php");
include("./../class/class.phpmailer.php");

$lockfile = realpath("./../")."/lock/sendmail";
// 注册关闭回调函数
register_shutdown_function('unlink', $lockfile);
$cc = new CSendMail_S();
exit();

class CSendMail_S
{
	public $logfile = "";
	public $mysql = null;
	/* 构造函数 */
	function __construct(){
		global $lockfile;
		$this->logfile = realpath("./../")."/log/sendmail.log";
		/*发送邮件操作类*/
		$fp = fopen($lockfile, "w");
		if( !$fp ){
			return;
		}
		if( !flock($fp, LOCK_EX | LOCK_NB) ){
			DbgPrint($this->logfile, "正在发送邮件");
			return;
		}
		DbgPrint($this->logfile, "开始发送邮件");
		$this->mysql = new QuickMySQL();
		try{
			while( $this->OnSendMail() ){
				sleep(1);
			}
		} catch (Exception $e){
			DbgPrint($this->logfile, "发送邮件操作出现异常" . $e->getMessage());
		}
		// 退出
		flock($fp, LOCK_UN);
		fclose($fp);
		DbgPrint($this->logfile, "发送邮件完成");
	}
	/* 析构函数 */
	function __destruct(){
		global $lockfile;
		if( file_exists($lockfile) )
			unlink($lockfile);
	}
	/*发送邮件*/
	function OnSendMail(){
		/*查询当前最小发送邮件的编号*/
		$sql = "select id,sm_subject,sm_to,sm_body from t_sendmail_queue where success=0 order by id asc limit 1";
		$ret = false;
		if( $this->mysql && !($res = $this->mysql->Query($sql)) ){
			DbgPrint($this->logfile, "连接数据库失败");
			return false;
		}
		// 获取数据
		if( $row = mysql_fetch_row($res) ){
			$id = $row[0];
			$subject = $row[1];
			$tos = $row[2];
			$body = $row[3];
			$ret = true;
		}
		mysql_free_result($res);
		if( !$ret ){
			DbgPrint($this->logfile, "没有要发送的数据");
			return false;
		}
		$toa = explode(";", $tos);
		$ret = false;
		foreach($toa as $to){
			try{
				if( !($ret = $this->MassSend($id,$to, $subject, $body)) ){
					DbgPrint($this->logfile, "群发邮件用户{$to}失败.");
					return false;
				} else {
					// 全部发送成功
					$this->mysql->Query("update t_sendmail_queue set success=1 where id={$id}");
				}
			} catch (Exception $e) {
				DbgPrint($this->logfile, "群发邮件用户{$to}异常:" . $e->getMessage());
				return false;
			}
		}
		return $ret;
	}
	/*发送用户组邮件*/
	function MassSend($id, $to, $subject, $body){
		$this->mysql->Query("insert into t_send_log(s_type,s_id) values('{$to}', {$id})");
		$this->mysql->Query("update t_sendmail_queue set first_t=curdate() where isnull(first_t) and id = {$id}");
		// 查询用户
		$res = $this->mysql->Query("select id,email from t_user_vm where sem_n < {$id} order by id asc");
		$this->mysql->Query("update t_send_log set count_all=" . mysql_num_rows($res)
				. " where s_type='{$to}' and s_id={$id}");
		while( $row = mysql_fetch_row($res) ){
			// 操作数据
			$uid = $row[0];
			$email = $row[1];
			if( !$this->mysql->Begin() )
				return false;
			// 写发送过标记
			// 发送邮件
			if( $this->SendMail($email, $subject, $body) ){
				// 成功标记
				$this->mysql->Query("update t_sendmail_queue set count_s = count_s + 1 where id={$id}");
				$this->mysql->Query("update t_user_vm set sem_s = sem_s + 1 where id={$uid}");
			} else {
				// 写失败标记
				$this->mysql->Query("update t_sendmail_queue set count_f = count_f + 1 where id={$id}");
				$this->mysql->Query("update t_user_vm set sem_f = sem_f + 1 where id={$uid}");
			}
			$this->mysql->Query("update t_user_vm set sem_n = {$id} where id={$uid}");
			$this->mysql->Query("update t_send_log set count_send = count_send + 1 where s_type='{$to}' and s_id={$id}");
			if( !$this->mysql->Commit() )
				return false;
		}
		mysql_free_result($res);
		return true; // 发送成功
	}
	/* 发送一封邮件 */
	function SendMail($email, $subject, $body){
		$mailreg = "/^([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?$/i";
		if( !preg_match($mailreg, $email) )
			return true;
		// 发送邮件
		global $sendmail_host, $sendmail_port, $sendmail_user, $sendmail_pwd;
		global $sendmail_from, $sendmail_from_name;
		
		$mail = new PHPMailer();
		$mail->CharSet = "UTF-8"; // 邮件编码
		$mail->Encoding = "base64";
		//$mail->AddCustomHeader("Content-Transfer-Encoding:base64");
		$mail->IsSMTP(); // 设定使用SMTP服务
		$mail->SMTPAuth = true;
		$mail->SMTPSecure = "ssh";
		$mail->Host = $sendmail_host; // 邮箱主机
		$mail->Port = $sendmail_port; // 端口号
		$mail->Username = $sendmail_user; // 用户名
		$mail->Password = $sendmail_pwd; // 密码
		$mail->SetFrom($sendmail_from, $sendmail_from_name); // 设置发件人
		$mail->Subject = $subject; // 标题
		$mail->IsHTML(true);
		$mail->Body = $body;
		$mail->AddAddress($email);
		
		return $mail->Send();
	}
}
?>